package com.cheyunkeji.er.activity.evaluate;

import android.Manifest;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.print.PrintAttributes;
import android.print.PrintManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.adapter.MyPrintAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.fast_evaluate.PushListEvaluater;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.utils.DownloadUtil;
import com.cheyunkeji.er.view.SDialog;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;
import com.google.gson.Gson;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.WebChromeClient;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.shareboard.ShareBoardConfig;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.appcompat.app.AlertDialog;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;
import pub.devrel.easypermissions.EasyPermissions;

import static com.cheyunkeji.er.utils.version.UpdatePresenter.WRITE_EXTERNAL_STORAGE;

public class EvaluateReportActivity extends BaseActivity
    implements SDialog.SDialog2Listener, UMShareListener {

  private static final String TAG = EvaluateReportActivity.class.getSimpleName();

  @BindView(R.id.v_topbar)
  TopBar vTopbar;

  @BindView(R.id.ll_webview)
  LinearLayout ll_webview;

  private String[] data = null;
  private Spinner spinner;
  private TextView cancel;
  private TextView confirm;

  private AlertDialog alertDialog;
  private List<String> spinnerList;
  private int spinnerSelect = 0;
  private PushListEvaluater pushListEvaluater;
  private SDialog dialog;
  private boolean sms = false, pushBoolean = false;
  private ShareAction mShareAction;

  @Override
  public void onStart(SHARE_MEDIA platform) {}

  @Override
  public void onResult(SHARE_MEDIA platform) {
    SToast.show("分享成功");
  }

  @Override
  public void onError(SHARE_MEDIA platform, Throwable t) {
    SToast.show("分享失败");
  }

  @Override
  public void onCancel(SHARE_MEDIA platform) {
    SToast.show("分享取消了");
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    /** attention to this below ,must add this* */
    UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
  }

  /** 屏幕横竖屏切换时避免出现window leak的问题 */
  @Override
  public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    mShareAction.close();
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    UMShareAPI.get(this).release();
  }

  @Override
  protected void init() {

    setContentView(R.layout.er_activity_evaluate_report);
    ButterKnife.bind(this);

    /*增加自定义按钮的分享面板*/
    mShareAction =
        new ShareAction(this)
            .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                .addButton("复制链接","copy_link","copy_link","copy_link")
            .setShareboardclickCallback(
                new ShareBoardlistener() {
                  @Override
                  public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                    if(share_media  == null) {
                      if (snsPlatform.mKeyword.equals("copy_link")) {
                        ClipboardManager cmb = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
                        cmb.setText(data[0]);
                        SToast.show("复制链接成功", Gravity.CENTER);
                      }
                    }else{
                      SToast.show("暂未开放", Gravity.CENTER);
//                      UMWeb web = new UMWeb(data[0]);
//                      web.setTitle("估价报告");
//                      web.setDescription(data[4]);
//                      UMImage umImage;
//                      if (TextUtils.isEmpty(data[5])) {
//                        umImage = new UMImage(FastEvaluateReportActivity.this, R.drawable.logo);
//                      } else {
//                        //                            umImage = new
//                        // UMImage(FastEvaluateReportActivity.this,data[5]);
//                        umImage = new UMImage(FastEvaluateReportActivity.this, R.drawable.logo);
//                      }
//                      web.setThumb(umImage);
//                      new ShareAction(FastEvaluateReportActivity.this)
//                              .withMedia(web)
//                              .setPlatform(share_media)
//                              .setCallback(FastEvaluateReportActivity.this)
//                              .share();
                    }
                  }
                });
  }

  @Override
  protected void initView() {
    vTopbar.setTitle("车辆全面评估报告");
    vTopbar.setLeftBack();
    vTopbar.setRight("打印", -1, this);
    vTopbar.vShare.setVisibility(View.VISIBLE);
    vTopbar.vShare.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            ShareBoardConfig config = new ShareBoardConfig();
            config.setMenuItemBackgroundShape(ShareBoardConfig.BG_SHAPE_NONE);
            mShareAction.open(config);
          }
        });

    if (null != getIntent().getStringArrayExtra("data")) {
      data = getIntent().getStringArrayExtra("data");
      //            wvContainer.getSettings().setJavaScriptEnabled(true);
      //            wvContainer.getSettings().setBlockNetworkImage(false);
      //            wvContainer.setWebViewClient(new WebViewClient());
      //            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
      //
      // wvContainer.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
      //            wvContainer.loadUrl(data[0]);

      AgentWeb mAgentWeb =
          AgentWeb.with(this) // 传入Activity
              .setAgentWebParent(ll_webview, new LinearLayout.LayoutParams(-1, -1))
              .useDefaultIndicator()
              .createAgentWeb()
              .ready()
              .go(data[0]);

      mAgentWeb
          .getWebCreator()
          .getWebView()
          .setWebChromeClient(
              new WebChromeClient() {
                @Override
                public void onReceivedTitle(WebView view, String title) {
                  super.onReceivedTitle(view, title);
                }

                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                  super.onProgressChanged(view, newProgress);
                  mAgentWeb.getIndicatorController().setProgress(newProgress);
                }
              });

      mAgentWeb.getAgentWebSettings().getWebSettings().setUseWideViewPort(true);
      mAgentWeb.getAgentWebSettings().getWebSettings().setLoadWithOverviewMode(true);
    }

    View view =
        LayoutInflater.from(EvaluateReportActivity.this)
            .inflate(R.layout.er_dialog_push_evaluater, null);
    spinner = (Spinner) view.findViewById(R.id.dialog_push_spinner);
    cancel = (TextView) view.findViewById(R.id.dialog_push_cancel);
    confirm = (TextView) view.findViewById(R.id.dialog_push_confirm);
    alertDialog = new AlertDialog.Builder(this, R.style.dialog_style_dim_3).setView(view).create();

    cancel.setOnClickListener(this);
    confirm.setOnClickListener(this);
    spinner.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            spinnerSelect = position;
          }

          @Override
          public void onNothingSelected(AdapterView<?> parent) {}
        });

  }

  @Override
  protected void initData() {}

  @Override
  public void onClick(View v) {
    super.onClick(v);

    switch (v.getId()) {
      case R.id.vRight:
        // 打印
        if (!TextUtils.isEmpty(data[1])) {
          String[] params = new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE};
          if (EasyPermissions.hasPermissions(this, params)) {
            doPostRequest(HttpConstants.PRINT_ARCHIVE_EVALUATE_REPORT, data[1]);
          } else {
            EasyPermissions.requestPermissions(this, "需要读写本地权限", WRITE_EXTERNAL_STORAGE, params);
          }
        }
        break;
      case R.id.dialog_push_cancel:
        alertDialog.dismiss();
        break;
      default:
        break;
    }
  }

  public void doPostRequest(final String httpUrl, final String pid) {
    HashMap<String, String> params = new HashMap<>();
    if (pid != null) {
      params.put("aid", pid);
    }
    ApiClient.postForm(
            httpUrl,
            params,
            new StringCallback() {
              @Override
              public void onError(Call call, Exception e, int id) {
                SToast.show("请求失败");
              }

              @Override
              public void onResponse(String response, int id) {
                Log.e("===" + TAG, httpUrl + "===" + response);
                Log.e(TAG + httpUrl, response + "=" + pushBoolean);
                if (pid != null) {
                  JSONObject jsonObject = null;
                  try {
                    jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("code") == 1) {
                      if (jsonObject.getString("msg").length() > 0) {
                        SToast.show(new JSONObject(response).getString("msg"));
                      } else {
                        JSONObject data = jsonObject.getJSONObject("data");
                        if (data != null) {
                          String filePath = data.getString("filepath");
                          if (!filePath.isEmpty()) {
                            confirmPrint(filePath);
                          }
                        } else {
                          SToast.show("提交成功");
                        }
                      }
                    } else {
                      SToast.show(new JSONObject(response).getString("msg"));
                    }
                  } catch (JSONException e) {
                    e.printStackTrace();
                  }
                }
              }

              @Override
              public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                if (!httpUrl.equals(HttpConstants.PRINT_EVALUATE_REPORT)) showDialog();
              }

              @Override
              public void onAfter(int id) {
                super.onAfter(id);
                if (!httpUrl.equals(HttpConstants.PRINT_EVALUATE_REPORT)) dismissDialog();
              }
            });
  }

  private void confirmPrint(String url) {
    final String name = "评估报告";
    final Activity activity = this;
    DownloadUtil.get()
        .download(
            url,
            Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator
                + "Download",
            name + ".pdf",
            new DownloadUtil.OnDownloadListener() {
              @Override
              public void onDownloadSuccess(File file) {
                Log.v("DOWN", "下載成功,文件已存入手机内部存储设备根目录下Download文件夾中");
                PrintManager printManager =
                    (PrintManager) activity.getSystemService(Context.PRINT_SERVICE);
                PrintAttributes.Builder builder = new PrintAttributes.Builder();
                builder.setColorMode(PrintAttributes.COLOR_MODE_COLOR);
                printManager.print(
                    name, new MyPrintAdapter(activity, file.getPath(), name), builder.build());
                Looper.prepare();
                Looper.loop();
              }

              @Override
              public void onDownloading(int progress) {
                Log.v("DOWN", "下載進度$progress");
              }

              @Override
              public void onDownloadFailed(Exception e) {
                Log.v("DOWN", e.toString());
              }
            });
  }

  @Override
  public void onClick(boolean l, View view) {
    Log.e(TAG + "ON", "dialog: " + l + "===" + pushBoolean);
    if (!l) {
      if (pushBoolean) {
        doPostRequest(HttpConstants.FAST_EVALUATE_PUSH_TO_ENTIRE_EVALUATE, data[1]);
      } else {
        if (Integer.parseInt(data[2]) == 1 || Integer.parseInt(data[2]) == 2) {
          doPostRequest(HttpConstants.SYNCHRONIZE_BUILD_SJ, data[1]);
        }
      }
    } else {
      SToast.show("取消");
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override
  public void onStart() {
    super.onStart();
  }

  @Override
  public void onStop() {
    super.onStop();
  }
}
